<?php
/**
 * User: @sunyu
 * Date: 2019-12-10
 * Time: 11:48
 */

namespace Frieza\Modules\Search\Controllers;

use App\Http\Controllers\Controller;
use App\Pockets\GridDataModel as pGridDataModel;
use Doraemon\cache\SearchTagRedis;
use Doraemon\cache\Search\SearchResultLink;
use Doraemon\service\position\Api;
use Doraemon\service\search\SearchTab;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Illuminate\Http\Request;
use Encore\Admin\Widgets\Tab;
use Doraemon\model\SearchKeyword;
use Encore\Admin\Widgets\Form;
use Illuminate\Support\MessageBag;
use Doraemon\cache\SearchRecommendTag;
use Doraemon\cache\SearchTag;


class SearchController extends Controller
{
    const PAGE_SIZE = 20;

    public function __construct()
    {
        parent::__construct();
        Admin::script('$(".pjax-container").attr("id","pjax-container");');
    }

    private function _filterWhere($params){
        if(isset($params['_columns_'])){
            unset($params['_columns_']);
        }
        if(isset($params['_pjax'])){
            unset($params['_pjax']);
        }
        $page = isset($params['page']) ? $params['page'] : 1;
        $pageSize = isset($params['per_page']) ? $params['per_page'] : self::PAGE_SIZE;
        $limit = [($page - 1) * $pageSize, $pageSize];
        unset($params['page']);
        $where = [];
        foreach ($params as $_k => &$_v) {
            if ($_v <> '') {
                $where[$_k] = $_v;
            }
        }
        $data = [
            'LIMIT' => $limit,
        ];

        if (!empty($where)) {
            $data['AND'] = $where;
        }

        return $data;
    }

    public function index(Request $request, Content $content, $step)
    {
        $request = $request->all();
        $request = self::_filterWhere($request);

        $tab = new Tab();
        $tab->addLink('搜索建议', '/admin/search/index/1', $step==1);
        $tab->addLink('搜索结果', '/admin/search/index/2', $step==SearchKeyword::MATCH_TYPE_RES);

        return $content
            ->header('搜索-搜索词推荐词')
            ->breadcrumb(
                ['text' => '搜索-搜索词推荐词', 'url' => '/search/index']
            )
            ->body($tab)->row(self::listAction($request, $step));
    }

    public function listAction($request, $step)
    {
        $limitArr = $request['LIMIT'];
        $where = [
            'recommend_keyword' => (string) $request['AND']['recommend_keyword'],
            'show_type' => (array) $request['AND']['show_type'],
            'content_type' => (array) $request['AND']['content_type'],
        ];
        if($request['AND']['input_keyword']) {
            $where['input_keyword[~]'] = array($request['AND']['input_keyword']);
        }
        $where = array_filter($where);
        $lists = SearchKeyword::getKeywordsByMatchType($step, $limitArr, $where);
        $lists_all = SearchKeyword::getKeywordsByMatchType($step, [], $where);

        $gridModel = new pGridDataModel($lists, count($lists_all), [
            'perPage' => $request['per_page'] ? : $request['LIMIT'][1]
        ]);
        $listGrid = Admin::grid($gridModel, function (Grid $grid) use ($step) {
            $grid->disableExport();
            $grid->disableRowSelector();

            $grid->filter(function (Grid\Filter $filter) {
                $filter->disableIdFilter();
                $filter->column(1 / 2, function ($filter) {
                    $filter->equal('input_keyword', '搜索词')->placeholder('搜索词(模糊匹配)');
                });

                $filter->column(1 / 2, function ($filter) {
                    $filter->equal('recommend_keyword', '推荐词')->placeholder('推荐词(精确匹配)');
                });

                $filter->column(1 / 2, function ($filter) {
                    $filter->equal('content_type', '内容类型')->checkbox([
                        1   => '运营内容',
                        2    => '广告'
                    ]);
                });

                $filter->column(1 / 2, function ($filter) {
                    $filter->equal('show_type', '展示时间')->checkbox([
                        1   => '永久',
                        2    => '暂时'
                    ]);
                });

            });

            $grid->column('id');
            $grid->column('input_keyword', '搜索词')->width(150);

            if ($step == SearchKeyword::MATCH_TYPE_RES) {
                $grid->column('link', '跳转链接')->linkSelect(false);
            } else {
                $grid->column('recommend_keyword', '推荐词')->width(150);
            }
//            $grid->column('show_type', '展示时间')->width(150)->replace(SearchKeyword::SHOW_TYPE);
            $grid->column('content_type', '内容类型')->width(150)->replace(SearchKeyword::CONTENT_TYPE);
            $grid->column('start_time', '开始展示时间');
            $grid->column('end_time', '展示结束时间')->display(function () {
                return $this->show_type == SearchKeyword::SHOW_TYPE_FOREVER ? SearchKeyword::SHOW_TYPE[SearchKeyword::SHOW_TYPE_FOREVER] : $this->end_time;
            });
            $grid->column('addtime', '添加时间');
            $grid->column('edittime', '修改时间');
            if ($step == SearchKeyword::MATCH_TYPE_SUGG) $grid->column('keyword_sort', '排序');
            $grid->column('admin_id', '操作人')->display(function(){
                if(!$this->admin_id) {
                    return '暂无';
                }else{
                    return Admin::user()->find($this->admin_id)->name;
                }
            });

        });

        $list = $listGrid->render();

        return $list;
    }

    //
    public function edit(Request $request,Content $content, $step, $id = 0)
    {
        $request = $request->all();
        if($id == 0) {
            return $content
                ->header('搜索-搜索词推荐词')
                ->breadcrumb(
                    ['text' => '搜索-搜索词推荐词', 'url' => '/search/index/'.$step],
                    ['text' => '添加搜索词', 'url' => '/search/index/'.$step.'/create']
                )
                ->body(self::editAction($request, $step, $id , True));
        } else {
            return $content
                ->header('搜索-搜索词推荐词')
                ->breadcrumb(
                    ['text' => '搜索-搜索词推荐词', 'url' => '/search/index/'.$step],
                    ['text' => '修改搜索词', 'url' => '/search/index/'.$step.'/'.$id.'/edit']
                )
                ->body(self::editAction($request, $step, $id, False));
        }
    }

    public function editAction($request, $step, $id = 0, $isCreate = false)
    {
        if($isCreate) {
            $info['match_type'] = $step;
            $form = new Form($info);
            $form->hidden('match_type');
            if ($step == SearchKeyword::MATCH_TYPE_RES) {
                $form->text('input_keyword', '搜索词')->required('不能为空');
             } else {
                $form->text('recommend_keyword', '推荐词')->setWidth(4, 2)->required('不能为空')->help('20字以内');
                $form->text('input_keyword', '标签词')->required('不能为空')->placeholder('以英文逗号分隔');
            }
       } else {
            $info = SearchKeyword::getKeywordById($id);
            if(isset($info['link_type']) && $info['link_type']) {
                $info['link'] = [
                    'link_type' => $info['link_type'],
                    'link_params' => (string)$info['link_params'],
                    'link_url' => (string)json_decode($info['link_params'], true)['url']
                ];
            }
            $form = new Form($info);
            $form->hidden('id');
            $form->hidden('match_type');
            if ($step == SearchKeyword::MATCH_TYPE_RES) {
                $form->text('input_keyword', '搜索词')->required('不能为空');
            } else {
                $form->text('recommend_keyword', '推荐词')->setWidth(4, 2)->required('不能为空')->help('20字以内')->readonly();
                $form->text('input_keyword', '标签词')->required('不能为空')->placeholder('以英文逗号分隔')->readonly();
            }
      }


        $form->setWidth(3, 2)->radio('show_type', '展示时间')->options(SearchKeyword::SHOW_TYPE)->default(SearchKeyword::SHOW_TYPE_FOREVER)->help('选择永久不需要填写结束时间');
        $form->setWidth(3, 2)->radio('content_type', '内容类型')->options(SearchKeyword::CONTENT_TYPE)->default(SearchKeyword::CONTENT_TYPE_BUS)->help('仅做备注，不影响展示规则');
        $form->linkSelect('link', '跳转链接');
        $form->datetime('start_time', '开始展示时间')->required('不能为空');
        $form->datetime('end_time', '展示结束时间')->help('展示时间为永久时此项不生效，为非必填项');
        if ($step == SearchKeyword::MATCH_TYPE_SUGG) $form->number('keyword_sort', '排序')->help('相同搜索词展示排序大的推荐词')->required('不能为空')->default(0);

        $action = $step == SearchKeyword::MATCH_TYPE_RES ? '/admin/search/index/saveSearch' : '/admin/search/index/save';
        $form->action($action);

        return $form->render();
    }

    public function del($step, $id)
    {
        $status = true;
        $message = '删除成功';
        try {
            $info = SearchKeyword::getKeywordById($id);
            if (!$info) throw new \Exception('信息不存在或者已删除');

            if ($info['match_type'] == SearchKeyword::MATCH_TYPE_RES) {
                //更新数据库状态
                $rs = SearchKeyword::del($id);
                if(!$rs) throw new \Exception('更新数据库状态失败');

                SearchResultLink::delItem('');
            } else {
                if(isset($info['input_keyword']) && $info['input_keyword']) {
                    $tags = explode(',', $info['input_keyword']);
                    foreach($tags as $tag) {
                        $old_rds = SearchRecommendTag::getRecommend($tag);
                        if($id) {
                            if(in_array($id, $old_rds)) {
                                SearchRecommendTag::deleteTagRecomm($tag, $id);
                            }
                        }
                    }
                }

                //更新数据库状态
                $rs = SearchKeyword::del($id);
                if(!$rs) throw new \Exception('更新数据库状态失败');

                //删除缓存
                //SearchTag::delete($id);
				SearchTagRedis::delItem($id);
            }
        } catch (\Exception $e) {
            $status = false;
            $message = "删除失败," . $e->getMessage();
        }

        return response()->json([
            'status' => $status,
            'message' => $message,
        ]);
    }

    public function save(Request $request)
    {
        $input_keyword = $request->input('input_keyword', '');
        $show_type = $request->input('show_type', '');
        $content_type = $request->input('content_type', '');
        $start_time = $request->input('start_time', '');
        $end_time = $request->input('end_time', '');
        $link_type = $request->input('link_type', '');
        $link_params = json_encode($request->input('link_params', []));
        $match_type = $request->input('match_type', '');
        $id = $request['id'];

        try {
            //校验数据
            if($show_type == 2 && (!$end_time || strtotime($end_time) <= strtotime($start_time))) {
                throw new \Exception('展示时间配置不正确');
            }

            if(empty($link_type)) throw new \Exception('跳转链接不能为空');

            if (strlen($input_keyword) == 0) throw new \Exception('搜索词不能为空');

            $data = [
                'match_type' => $match_type,
                'content_type' => $content_type,
                'input_keyword' => $input_keyword,
                'show_type' => $show_type,
                'end_time' => $end_time,
                'start_time' => $start_time,
                'link_type' => $link_type,
                'link_params' => $link_params,
                'admin_id' => Admin::user()->id,
            ];

            if($id) {
                $data['edittime'] = date('Y-m-d H:i:s', time());
                SearchKeyword::updateData($id, $data);
            } else {
                $data['addtime'] = date('Y-m-d H:i:s', time());
                SearchKeyword::addData($data);
            }

            if ($match_type == SearchKeyword::MATCH_TYPE_RES) SearchResultLink::delItem('');

            return redirect('/admin/search/index/' . $match_type)->with(compact('success'));
        } catch (\Exception $e) {
            $error = new MessageBag([
                'title' => '操作失败,' . $e->getMessage(),
            ]);
            return back()->withInput()->with(compact('error'));
        }


    }

    public function editSubmit(Request $request)
    {
        $request = $request->all();
        $id = (int) $request['id'];

        $data = [
            'recommend_keyword' => $request['recommend_keyword'],
            'show_type' => $request['show_type'],
            'content_type' => $request['content_type'],
            'input_keyword' => $request['input_keyword'],
            'link_type' => $request['link_type'],
            'link_params' => json_encode($request['link_params']),
            'start_time' => $request['start_time'],
            'end_time' => $request['end_time'],
            'keyword_sort' => $request['keyword_sort'],
            'admin_id' => Admin::user()->id,
        ];

        //校验数据
        if($data['show_type'] == 2 && (!$data['end_time'] || strtotime($data['end_time']) <= strtotime($data['start_time']))) {
            $error = new MessageBag([
                'title' => '展示时间为暂时的搜索词一定要配结束时间哦'
            ]);
            return redirect('/admin/search/index/1')->with(compact('error'));
        }
        if(empty($data['link_type']) || empty($data['link_params'])) {
            $error = new MessageBag([
                'title' => '推荐词的链接一定要配哦！'
            ]);
            return redirect('/admin/search/index/1')->with(compact('error'));
        }

        if($id) {
            $data['edittime'] = date('Y-m-d H:i:s', time());
            $rs = SearchKeyword::updateData($id, $data);
            //SearchTag::delete($id);
			SearchTagRedis::delItem($id);
            $rds_data = array_merge(['id'=>$id], $data);
            //SearchTag::setValue($id, $rds_data, 864000);
			SearchTagRedis::setItem($id, $rds_data,864000);
        } else {
            $data['match_type'] = $request['match_type'];
            $data['addtime'] = date('Y-m-d H:i:s', time());
            $rs = SearchKeyword::addData($data);
            $rds_data = array_merge(['id'=>$rs], $data);
            //SearchTag::setValue($rs, $rds_data, 864000);
	        SearchTagRedis::setItem($rs, $rds_data,864000);
        }

        if($rs) {
            //存redis
            $tags = explode(',', $data['input_keyword']);
            foreach($tags as $tag) {
                $old_rds = SearchRecommendTag::getRecommend($tag);
                if($id) {
                    if(!in_array($id, $old_rds)) {
                        SearchRecommendTag::addTag($tag, $id);
                    }
                } else {
                    if(!in_array($rs, $old_rds)) {
                        SearchRecommendTag::addTag($tag, $rs);
                    }
                }
            }

            $success = new MessageBag([
                'title' => '操作成功'
            ]);
            return redirect('/admin/search/index/1')->with(compact('success'));
        } else {
            $error = new MessageBag([
                'title' => '操作失败'
            ]);
            return redirect('/admin/search/index/1')->with(compact('error'));
        }


    }



}